

package com.xxtx.trade.common;


import com.xxtx.trade.common.exception.BusinessException;
import com.xxtx.trade.common.util.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName : WebExceptionHandler <br/>
 * Function  : 统一参数校验错误返回. <br/>
 * Reason    : 参数校验. <br/>
 */
@ControllerAdvice
public class WebExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(WebExceptionHandler.class);

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result<Object> handleBindException(HttpServletRequest req, BindException be) {
        log.warn(be.getMessage(), be);
        Result<Object> result = new Result<>(1, "参数错误");

        if (be.hasErrors()) {
            StringBuilder sb = new StringBuilder("[");
            List<ObjectError> objErrs = be.getAllErrors();
            for (ObjectError err : objErrs) {
                sb.append(err.getDefaultMessage()).append(";");
            }
            sb.append("]");
            result.setMessage(result.getMessage() + sb.toString());
        }

        return result;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<Object> handleMethodArgumentNotValidException(HttpServletRequest req,
                                                                MethodArgumentNotValidException manve) {
        log.warn(manve.getMessage(), manve);
        Result<Object> result = new Result<>(1, "参数错误");

        BindingResult bindingResult = manve.getBindingResult();

        if (bindingResult != null && bindingResult.hasErrors()) {
            StringBuilder sb = new StringBuilder("[");
            List<ObjectError> objErrs = bindingResult.getAllErrors();
            for (ObjectError err : objErrs) {
                sb.append(err.getDefaultMessage()).append(";");
            }
            sb.append("]");
            result.setMessage(result.getMessage() + sb.toString());
        }

        return result;
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public Result<Object> businessException(BusinessException be ) {
        return Result.error(be.getCode(),be.getMessage());
    }

}
